// C11:SimplePriorities.cpp
//  Shows the use of thread priorities.
//  {L} ZThread
#include "zthread/Thread.h"
#include <iostream>
#include <ostream>

using namespace ZThread;
using namespace std;

const double pi = 3.141592;
const double e = 2.718281;

class SimplePriorities : public Runnable {
  int counDown;
  volatile double d; // No optimization
  int id;

public:
  SimplePriorities(int ident = 0) : counDown(5), id(ident) {}
  ~SimplePriorities() { cout << id << " completed" << endl; }

  friend ostream &operator<<(ostream &os, const SimplePriorities &sp) {
    return os << "#" << sp.id << " priority: " << Thread().getPriority()
              << " count: " << sp.counDown;
  }

  void run() {
    while (true) {
      // An expensive, interruptable operation:
      for (int i = 1; i < 100000; i++) {
        d = d + (pi + e) / double(i);
      }
      cout << *this << endl;
      if (--counDown == 0) {
        return;
      }
    }
  }
};

int main(void) {
  try {
    Thread high(new SimplePriorities);
    high.setPriority(High);
    for (int i = 0; i < 5; i++) {
      Thread low(new SimplePriorities(i));
      low.setPriority(Low);
    }
  } catch (Synchronization_Exception &e) {
    cerr << e.what() << endl;
  }
}
